package com.bys.admin.system.service.impl;

import com.bys.admin.system.entity.SysFile;
import com.bys.admin.system.mapper.SysFileMapper;
import com.bys.admin.system.service.ISysFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bys
 * @since 2025-01-24
 */
@Service
@Slf4j
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements ISysFileService {
    @Value("${ssh.ip}")
    private String  ip;
    @Value("${ssh.port}")
    private String  port;
    @Value("${ssh.username}")
    private String  username;
    @Value("${ssh.password}")
    private String  password;
    @Value("${ssh.remoteFilePath}")
    private String remoteFilePath;
    @Value("${ssh.fileUri}")
    private String fileUri;
    @Override
    public String uploadFile(InputStream inputStream,String fileName) {
        JSch jsch = new JSch();
        Session session = null;
        ChannelSftp channelSftp = null;
        String filePath = fileUri.concat("/").concat(fileName);

        try {
            // 创建 SSH 会话
            session = jsch.getSession(username, ip, Integer.parseInt(port));
            session.setPassword(password);
            // 禁用严格主机密钥检查
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            // 连接到服务器
            session.connect();

            // 打开 SFTP 通道
            Channel channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;

            // 上传文件
            channelSftp.put(inputStream, remoteFilePath.concat("/").concat(fileName));
            log.info("文件上传成功！");


        } catch (JSchException | SftpException e) {
            e.printStackTrace();
        } finally {
            // 关闭 SFTP 通道和 SSH 会话
            if (channelSftp != null) {
                channelSftp.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
        return filePath;

    }
}
